package com.tarry.service.impl;

import com.google.common.base.Preconditions;
import com.tarry.common.RequestHolder;
import com.tarry.dao.SysRoleMapper;
import com.tarry.exception.ParamException;
import com.tarry.model.entity.SysRole;
import com.tarry.model.vo.RoleVo;
import com.tarry.service.SysRoleService;
import com.tarry.util.BeanValidator;
import com.tarry.util.IpUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class SysRoleServiceImpl extends BaseService<SysRole> implements SysRoleService {

    @Autowired
    private SysRoleMapper sysRoleMapper;
//    @Autowired
//    private SysRoleUserMapper sysRoleUserMapper;
//    @Autowired
//    private SysRoleAclMapper sysRoleAclMapper;
//    @Autowired
  //  private sysRoleUserMapper sysUserMapper;
  //  @Autowired
   // private SysLogService sysLogService;


    @Override
    public SysRole findByKeyword(String keyword) {
        return null;
    }

    @Override
    public void save(RoleVo entity) {
        BeanValidator.check(entity);
        if (checkExist(entity.getName(), entity.getId())) {
            throw new ParamException("角色名称已经存在");
        }
        SysRole role = SysRole.builder()
                .name(entity.getName())
                .status(entity.getStatus())
                .type(entity.getType())
                .remark(entity.getRemark()).build();
        setOpratorInfo(role);
        sysRoleMapper.insertSelective(role);
       // sysLogService.saveRoleLog(null, role);
    }

    @Override
    public void update(RoleVo entity) {
        BeanValidator.check(entity);
        if (checkExist(entity.getName(), entity.getId())) {
            throw new ParamException("角色名称已经存在");
        }
        SysRole before = sysRoleMapper.selectByPrimaryKey(entity.getId());
        Preconditions.checkNotNull(before, "待更新的角色不存在");

        SysRole after = SysRole.builder()
                .id(entity.getId())
                .name(entity.getName())
                .status(entity.getStatus())
                .type(entity.getType())
                .remark(entity.getRemark()).build();
        setOpratorInfo(after);
        sysRoleMapper.updateByPrimaryKeySelective(after);
        //sysLogService.saveRoleLog(before, after);
    }

    @Override
    public void delete(int id) {

    }

    private boolean checkExist(String name, Integer id) {
        return sysRoleMapper.countByName(name, id) > 0;
    }

    public List<SysRole> getAll() {
        return sysRoleMapper.getAll();
    }
}
